; p11.ss

; 不要把object中的value看成离散状态，而是一个连续变化的过程

; 设计程序就是设计语言

; stream 的选择函数head tail和构造函数cons-stream, THE-EMPTY-STREAM
; (cons-stream x y)
; (head stream)
; (tail stream)

; For any x+y
; (head (cons-stream x y)) => x
; (tail (cons-stream x y)) => y

; map
(define (map-stream proc s)
    (if 
        (cons-stream
         (proc (head s))
         (map-stream proc (tail s)))))

; filter
(define (filter pred s)
  (cond
    ((empty-stream? s) the-empty-stream)
    ((pred (head s))
     (cons-stream (head s) (filter pred (tail s))))
    (else (filter pred (tail s)))))

; reduce
(define (accumulate combiner init-val s)
  (if (empty-stream? s)
      init-val
      (combiner (head s)
                (accumulate combiner init-val (tail s)))))

; 枚举树
(define (enumerate-tree tree)
  (if (leaf-node? tree)
      (cons-stream tree the-empty-stream)
      (append-streams
       (enumerate-tree (left-branch tree) (right-branch tree)))))

; 合并表
(define (append-streams s1 s2)
    (if (empty-stream? s1)
        s2
        (cons-stream (head s1)
         (append-streams (tail s1) s2))))

; 枚举一个区间
(define (enum-interval low high)
  (if (> low high)
      the-empty-stream
      (cons-stream low
       (enum-interval (1+ low) high))))


; 计算树上的奇数平方和
(define (sum-odd-squares tree)
    (accumulate + 0
                (map square
                     (filter odd (enumerate-tree tree)))))


; fib
(define (odd-fibs n)
    (accumulate cons '()
                (filter odd 
                        (map fib (enum-interval 1 n)))))


; 流，组建了约定的接口，枚举->过滤->运算->结合

; 回溯搜索